package com.mdn.steelcase.controller;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mdn.steelcase.model.DocumentEntity;
import com.mdn.steelcase.service.DocumentService;

@Controller
@RequestMapping("/document")
public class DocumentController {

	@Autowired
	DocumentService documentService;
	@Autowired
	protected ObjectMapper jsonMapper;
	
	@RequestMapping(value = "/{name}", method = RequestMethod.GET)
	public String editGet(@PathVariable String name, ModelMap map) {
		DocumentEntity document = documentService.findSingleByColumn("name", name);
		if(document != null){
			map.put("documentForm", document);
		}else{
			map.put("name", name);
		}
		return "document/edit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST, produces= "application/json; charSet=UTF-8")
	public @ResponseBody String editPost(DocumentEntity documentForm, BindingResult result) throws JsonGenerationException, JsonMappingException, IOException {
		if (result.hasErrors()) {
			return jsonMapper.writeValueAsString(result); 
        }
		documentService.update(documentForm);
		return jsonMapper.writeValueAsString("OK"); 
	}
}
